package com.neusoft.ruidaozaixian.controller.activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.neusoft.ruidaozaixian.R;
import com.neusoft.ruidaozaixian.model.bean.LoginBean;
import com.neusoft.ruidaozaixian.model.bean.UserBean;
import com.neusoft.ruidaozaixian.util.CookieJarImpl;
import com.neusoft.ruidaozaixian.util.baseinfo.Connectinfo;
import com.neusoft.ruidaozaixian.util.store.PersistentCookieStore;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class LoginActivity extends AppCompatActivity{

    private EditText text;
    private EditText username;
    private EditText password;
    private final static String TAG = "LoginActivity";
    public static OkHttpClient mOkHttpClient;
    private ImageView image;
    private Button button;
    private CheckBox ckLogin;
    public static String s;
    private String code;
    private String user;
    private String pwd;
    private OkHttpClient.Builder builder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Log.i(TAG, "onCreate");
        text = (EditText) findViewById(R.id.identifyingCode);
        image = (ImageView) findViewById(R.id.image);
        button = (Button) findViewById(R.id.bt_login_login);
        username = (EditText) findViewById(R.id.et_login_name);
        password = (EditText) findViewById(R.id.et_login_pwd);
        ckLogin = (CheckBox) findViewById(R.id.ckLogin);

        builder = new OkHttpClient.Builder();
        PersistentCookieStore persistentCookieStore = new PersistentCookieStore(getApplicationContext());
        CookieJarImpl cookieJarImpl = new CookieJarImpl(persistentCookieStore);
        builder.cookieJar(cookieJarImpl);
        mOkHttpClient = builder.build();
        getPicture();

    }
    public void login(View view){
        setCkLogin();
    }
    public void getPic(View view){
        getPicture();
    }
    private void getPicture() {

        //创建一个Request
        final Request request = new Request.Builder()
                .url(Connectinfo.identifyingCode)
                .build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            //失败的回调
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "errro");
            }

            //成功的回调
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //刷新ui，okhttp网络请求后，不是在主线程中，如果要刷新ui，必须的主线程中；
                if (response.isSuccessful()) {
                    InputStream is = response.body().byteStream();
                    Bitmap bm = BitmapFactory.decodeStream(is);
// // image.setImageBitmap(bm);
                    mHandler.sendEmptyMessage(0);
                    Message msg = new Message();
                    msg.obj = bm;//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                }
                Headers headers = response.headers();
                Log.d(TAG, "header " + headers);
                List<String> cookies = headers.values("Set-Cookie");
                String session = cookies.get(0);
                Log.d(TAG, "onResponse-size: " + cookies);
                s = session.substring(0, session.indexOf(";"));
                Log.i(TAG, "session is :" + s);
            }
        });
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //完成主界面更新,拿到数据
                    Bitmap bm = (Bitmap) msg.obj;
                    image.setImageBitmap(bm);

                    break;
                default:
                    break;
            }
        }

    };
    public void setCkLogin(){
        Log.i(TAG, "发这的s是： " + s);
        code = text.getText().toString().trim();
        user = username.getText().toString();
        pwd = password.getText().toString();
        if (TextUtils.isEmpty(user)) {
            username.setError("请输入用户名");
            username.requestFocus();
        } else if (TextUtils.isEmpty(pwd)) {
            password.setError("请输入密码");
            password.requestFocus();
        }
        //String pass = Md5Util.getMD5Str("123456");
        final Gson gson = new Gson();
        FormBody formBody = new FormBody.Builder()
                .add("username", username.getText().toString())
                .add("pwd", password.getText().toString())
                .add("imgcode", code)
                .build();
        final Request request = new Request.Builder()
                .addHeader("cookie", s)
                .url(Connectinfo.login)
                .post(formBody)
                .build();
        Call call2 = mOkHttpClient.newCall(request);
        //请求加入调度
        call2.enqueue(new Callback() {
            //失败的回调
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, e.getMessage());
            }

            //成功的回调
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //刷新ui，okhttp网络请求后，不是在主线程中，如果要刷新ui，必须的主线程中
                if (response.isSuccessful()) {
                    Gson gson = new Gson();
                    LoginBean bean = gson.fromJson(response.body().string(), LoginBean.class);
                    String loginFlag =bean.getLoginReturn().getLoginFlag();
                    String msg = bean.getLoginReturn().getLoginFlag();
                    System.out.println("bbbb"+loginFlag.equals("1"));
                    if(loginFlag.equals("1")==true){
                        UserBean userBean = new UserBean();
                        userBean.setUsername(loginFlag);
                        userBean.setPwd(pwd);
                        userBean.setImgcode(code);
                        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                        Bundle bundle = new Bundle();                           //创建Bundle对象
                        bundle.putSerializable(Connectinfo.USER_KEY,userBean);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        LoginActivity.this.finish();
                    }



                }




            }

        });
    }
}

